﻿using UnityEngine;
using System.Collections;
using evt;
using UnityEngine.UI;
using tools;
public class JoinRoomView : MonoBehaviour {

	private string RoomNumber = "";
	// Use this for initialization
	void Start () {
		ServerEventDispather.getInstance ().AddEventDispather (ServerEvent.SHOW_JOINROOM_VIEW,OpenView);
		EventTriggerListener.Get (gameObject).onClick = HideView;
		EventTriggerListener.Get (transform.GetChild(0).gameObject).onClick = OpenView;
		EventTriggerListener.Get (transform.Find("Clear").gameObject).onClick = ClearText;
		EventTriggerListener.Get (transform.Find("Join").gameObject).onClick = JoinRoom;
		for ( int i = 0 ; i < 10 ; i++ ) {
			EventTriggerListener.Get (transform.Find(i.ToString()).gameObject).onClick = Keys;
		}
	}

	private void ClearText(GameObject go){
		RoomNumber = "";
		SoundPlayer.play ("7571");
	}

	private void Keys(GameObject go){
		SoundPlayer.play ("7571");
		Debug.Log (RoomNumber.Length);
		if ( RoomNumber.Length < 6 ) {
			RoomNumber += go.name;
			if (RoomNumber.Trim().Length == 6 ) {
				GSocket.Send (ByteFactory.makeByte (621102,RoomNumber));
			}
		}
	}

	private void OpenView(object data){
		transform.localPosition = Vector3.zero;
	}

	private void HideView(object data){
		transform.localPosition = new Vector3(10000,0,0);
	}
	
	private void JoinRoom(object data){
		if (RoomNumber.Length > 0) {
			RoomNumber = RoomNumber.Substring (0, RoomNumber.Length - 1);
		}
	}

	// Update is called once per frame
	void Update () {


		for(int i = 0 ; i < 6;i++){
			if (RoomNumber.Length > i) {
				transform.GetChild (1).GetChild (i).GetComponent<Text> ().text = RoomNumber [i].ToString ();
			} else {
				transform.GetChild (1).GetChild (i).GetComponent<Text> ().text = "";
			}

		}

	}
}
